package com.example.controller;

import com.example.service.SysUserService;
import com.example.utils.MD5Utils;
import com.example.utils.MailUtils;
import com.example.utils.QiniuUtils;
import com.example.utils.Result;
import com.example.vo.MailVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Random;

/**
 * TODO
 * 工具控制器
 * @Comment：最难的一次作业
 * @Date: 2023/12/6
 */
@RestController
@RequestMapping("/tool")
@Api(tags = "工具类")
public class ToolController {

    @Autowired
    private QiniuUtils qiniuUtils;

    @Autowired
    private MailUtils mailUtils;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private SysUserService userService;

    @ApiOperation(value = "七牛云文件上传")
    @PostMapping("/upload")
    public Result upload(@RequestBody MultipartFile file) throws IOException {
        String url = qiniuUtils.upload(file.getInputStream(), file.getOriginalFilename());
        return Result.success("文件上传成功！", url);
    }

    @ApiOperation(value = "邮件找回密码")
    @PostMapping("/forget/password")
    public Result forget(@RequestBody MailVo mail) {
        mail.setSubject("413の个人健康管理平台");
        // 生成随机密码
        Random random = new Random();
        int password = 100000 + random.nextInt(1000000);
        // 将密码更新到用户信息
        userService.updatePwdByMail(mail.getReceivers()[0], passwordEncoder.encode(MD5Utils.md5(String.valueOf(password))));
        mail.setContent("您的新密码是: " + password + ", 请妥善保管喵");
        return Result.success(mailUtils.sendMail(mail));
    }
}
